package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.UnLikesMapper;
import com.heima.behavior.service.UnLikesService;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UnLikesServiceImpl extends ServiceImpl<UnLikesMapper, ApUnlikesBehavior> implements UnLikesService {
    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult unlikes(UnLikesBehaviorDto dto) {
        ApUser user = AppThreadLocalUtil.getUser();
        //cacheService.lRemove(user.getId() + "unlikes" + dto.getArticleId(), 0, 0 + "");
        ApUnlikesBehavior one = getOne(Wrappers.<ApUnlikesBehavior>lambdaQuery().eq(ApUnlikesBehavior::getArticleId, dto.getArticleId()));

        if (dto.getType() == 0) {
            if (one == null) {
                ApUnlikesBehavior apUnlikesBehavior = new ApUnlikesBehavior();
                apUnlikesBehavior.setCreatedTime(new Date());
                apUnlikesBehavior.setEntryId(user.getId());
                apUnlikesBehavior.setArticleId(dto.getArticleId());
                apUnlikesBehavior.setType(dto.getType());
                save(apUnlikesBehavior);
                cacheService.lLeftPush(user.getId() + "unlikes" + dto.getArticleId(), dto.getType() + "");
            } else {
                one.setType(dto.getType());
                updateById(one);
                cacheService.lLeftPush(user.getId() + "unlikes" + dto.getArticleId(), dto.getType() + "");
            }
        } else {
            one.setType(dto.getType());
            updateById(one);
            cacheService.lRightPop(user.getId() + "unlikes" + dto.getArticleId());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
